﻿#ifndef J_SIFTAREAEDITOR_H
#define J_SIFTAREAEDITOR_H

#include "../jcurve_global.h"
#include <QObject>
#include <QPainterPath>

// - class JAreaSift -

class QwtPlot;
class QwtPlotShapeItem;
class QwtWidgetOverlay;
class QMouseEvent;

class JSiftAreaEditor : public QObject
{
    Q_OBJECT
public:
    enum RegionType {
        RegionInvalid = -1,
        RegionTopLeft,
        RegionTop,
        RegionTopRight,
        RegionLeft,
        RegionCenter,
        RegionRight,
        RegionBottomLeft,
        RegionBottom,
        RegionBottomRight,
        RegionCount
    };

    explicit JSiftAreaEditor(QwtPlot *plot);
    ~JSiftAreaEditor();

    QwtPlot *plot();
    const QwtPlot *plot() const;

    //
    void clearShape();
    void addShape(const QPainterPath &path, const QString &title = QString(), bool notify = false);

    //
    void setShape(int index, const QPainterPath &path, bool notify = false);

    //
    QwtPlotShapeItem *shapeAt(int index) const;
    int shapeCount() const;

    bool eventFilter(QObject *object, QEvent *event);

    void drawOverlay(QPainter *painter) const;
    QRegion maskHint() const;

    bool isEnabled() const;

    //
    QList<QRectF> siftAreas() const;

    void setAxisAutoScale(bool enabled);

Q_SIGNALS:
    void siftAreaChanged(int index, const QRectF &rect);

public Q_SLOTS:
    virtual void setEnabled(bool on);

protected:
    void widgetMousePress(const QMouseEvent *event);
    void widgetMouseMove(const QMouseEvent *event);
    void widgetMouseRelease(const QMouseEvent *event);

private:
    bool focusItem(const QPoint &pos, bool press);
    bool moveItem(const QPoint &pos);
    void releaseItem(const QPoint &);
    QwtPlotShapeItem *itemAt(const QPoint &pos) const;
    void raiseItem(QwtPlotShapeItem *);
    void setItemVisible(QwtPlotShapeItem *item, bool on);
    QRegion maskHint(QwtPlotShapeItem *) const;

    static QwtPlotShapeItem *createShapeItem(const QPainterPath &path,
                                             const QString &title = QString());

    RegionType regionHit(const QPoint &pos) const;

private:
    bool d_isEnabled;
    QPointer<QwtWidgetOverlay> d_overlay;

    bool d_isMoved;
    bool d_isResized;

    // Mouse positions
    QPoint d_currentPos;
    bool d_mousePressed;
    RegionType d_regionPressed;
    QwtPlotShapeItem *d_editedItem;
    QCursor d_canvasCursor;
    QList<QwtPlotShapeItem *> siftShapes;
};

#endif // J_SIFTAREAEDITOR_H
